package cn.tworice.verify.auth;

import cn.tworice.verify.service.OnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("verify")
public class AuthServer {

    @Autowired
    private OnlineService onlineService;

    @PutMapping("online")
    public boolean online(String key, String token){
        return onlineService.online(key, token);
    }

    @GetMapping("onlineMap")
    public Map<String, String> onlineMap(){
        return onlineService.onlineMap();
    }

    @PostMapping("offline")
    public boolean offline(String key){
        return onlineService.offline(key);
    }

    @PostMapping("exist")
    public boolean exist(String key, String token) {
        return this.onlineService.exist(key, token);
    }

    /**
     * 核验用户请求
     * @param key 用户ID
     * @param token 用户Token
     * @param url 用户请求的地址
     * @return boolean 返回用户所请求的资源是否通过
     **/
    @PostMapping("auth")
    public boolean auth(String key, String token, String url){
        if(this.onlineService.exist(key, token)){
            return this.onlineService.authAdminResource(key, url);
        }
        return false;
    }

    /**
     * 添加用户拥有的资源列表缓存
     * @param adminID 用户ID
     * @param resources 资源列表
     * @return boolean 是否添加成功
     * @author 二饭 [2022/10/8]
     **/
    @PostMapping("cache")
    public boolean addAdminResources(@RequestParam("adminID") String adminID,@RequestParam("resources") String[] resources) {
        return onlineService.addAdminResources(adminID, resources);
    }
}
